<template>
  <div class="dept-tree">
    <div v-if="allDeptList.length" class="dept-header">
      <div class="header-crumb">
        <el-tooltip :open-delay="800" placement="top">
          <div slot="content" style="max-width: 300px;">{{ crumbName }}</div>
          <el-breadcrumb v-if="crumbList.length" separator="/">
            <el-breadcrumb-item
              v-for="(crumb, index) in crumbList"
              :key="crumb.id"
              :class="index !== crumbList.length - 1 && 'crumb-active'"
              @click.native="onCrumbChange(index)"
            >{{ crumb.departmentName }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-breadcrumb v-else separator="/">
            <el-breadcrumb-item>飞博共创</el-breadcrumb-item>
          </el-breadcrumb>
        </el-tooltip>
        <el-image :src="showIcon" class="icon" @click.native="hideLeft(false)"/>
      </div>
    </div>
    <div class="dept-container">
      <div v-loading="loading" class="page-container">
        <div v-if="curDeptList.length && isSign">
          <div v-for="item in formatSign(curDeptList)" :key="item.id" :style="{cursor: 'pointer'}" class="box" @click="getChildList(item)">
            <div class="box-content">
              <div class="text">{{ item.departmentName }}<span>({{ item.peopleNum }}人)</span></div>
              <div v-if="hasChildren(item)" class="next-level"><img :src="nextIcon" alt="">下级</div>
            </div>
          </div>
        </div>
        <div v-else-if="curDeptList.length">
          <div v-for="item in curDeptList" :key="item.id" :style="{cursor: 'pointer'}" class="box" @click="getChildList(item)">
            <div class="box-content">
              <div class="text">{{ item.departmentName }}<span>({{ item.peopleNum }}人)</span></div>
              <div v-if="hasChildren(item)" class="next-level"><img :src="nextIcon" alt="">下级</div>
            </div>
          </div>
        </div>
      </div>
      <EmptyPlaceholder v-if="isSign ? !formatSign(curDeptList).length : !curDeptList.length" empty-text="无子级经营体" />
    </div>
  </div>
</template>

<script>
// components
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
// api
import { getBusinessEntiy, getSignTargetEntiy } from '@/api/target';
// tool
import { isEmpty } from '@/utils/array';
import nextIcon from '@/assets/target/nextlevel.png';
import showIcon from '@/assets/target/tip_blue.png';

export default {
  components: { EmptyPlaceholder },
  model: {
    prop: 'curDept',
    event: 'changeValue'
  },
  props: {
    curDept: { // 当前级数
      type: Object,
      default: () => {
        return {};
      }
    },
    isSign: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      nextIcon, showIcon,
      deptTreeList: [],
      curDeptList: [],
      crumbList: [],
      loading: false,
      allDeptList: [] // 所有部门
    };
  },
  computed: {
    crumbName() {
      let str = '';
      const len = this.crumbList.length - 1;
      this.crumbList.forEach((item, index) => {
        if (index === len) {
          str += item.departmentName;
        } else {
          str += item.departmentName + '/';
        }
      });
      return str;
    }
  },
  created() {
    this.queryList();
  },
  methods: {
    formatSign(arr) {
      return arr.filter(item => item.isDepartment);
    },
    // 遍历将departmentId转换为id
    formatTreeId(tree) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].isDepartment && (tree[i].departmentId || tree[i].departmentId === 0)) {
          tree[i].id = tree[i].departmentId;
        }
        if (tree[i].children && tree[i].children.length) {
          this.formatTreeId(tree[i].children);
        }
      }
    },
    // 获取经营体部门
    async queryList(reset = true) {
      try {
        this.loading = true;
        const method = this.isSign ? getSignTargetEntiy : getBusinessEntiy;
        const result = await method();
        if (result && result.data) {
          this.allDeptList = result.data || [];
          if (this.isSign) {
            this.formatTreeId(this.allDeptList);
            // this.$emit('getDeptData', this.allDeptList);
          }
          if (!this.curDept.id) {
            this.$emit('changeValue', this.allDeptList[0]);
          }
          this.$nextTick(() => {
            this.resetCrumbList();
          });
        }
        this.loading = false;
      } catch (e) {
        this.loading = false;
      }
    },
    onCrumbChange(index) {
      if (index === -1) {
        this.crumbList = [];
        this.curDeptList = this.allDeptList;
        this.$emit('changeValue', this.allDeptList);
        this.$emit('freshData', true);
        return;
      }
      this.crumbList.splice(index + 1);
      const curDept = this.crumbList.slice(-1)[0];
      this.curDeptList = curDept.children;
      this.$emit('changeValue', curDept);
      this.$emit('freshData', true);
    },
    // tool
    getChildList(data) {
      // if (isEmpty(data.children)) return;
      this.crumbList.push(data);
      this.curDeptList = data.children || [];
      this.$emit('changeValue', data);
      this.$emit('freshData', true);
    },
    // 更新面包屑的当前列表的数据
    resetCrumbList() {
      const deptId = this.curDept.id;
      if (!deptId && deptId !== 0) return [];
      const matchData = JSON.parse(JSON.stringify(this.allDeptList));
      const crumbList = this.getPathByKey(deptId, matchData);
      this.crumbList = crumbList;

      const curDept = this.crumbList.slice(-1)[0];
      this.curDeptList = curDept.children || [];
    },
    getPathByKey(value, arr) {
      let tempPath = [];
      function getNodePath(curPath, node) {
        if (tempPath.length > 0) return;
        curPath.push(node);
        if (node.id === value) {
          tempPath = JSON.parse(JSON.stringify(curPath));
          return;
        }
        if (node.children && node.children.length > 0) {
          for (var i = 0; i < node.children.length; i++) {
            getNodePath(curPath, node.children[i]);
          }
          curPath.pop();
        } else {
          curPath.pop();
        }
      }
      for (let i = 0; i < arr.length; i++) {
        getNodePath([], arr[i]);
      }
      return tempPath;
    },
    hasChildren(data) {
      return !isEmpty(data.children);
    },
    hideLeft() {
      const obj = {
        isShowLeft: false,
        crumbList: this.crumbList
      };
      this.$emit('hideLeft', obj);
    }
  }
};
</script>

<style lang="scss" scoped>
.dept-tree {
  width: 320px;
  padding: 0px 20px 24px 20px;
  border-right: 1px solid #DDE1EA;
  flex-shrink: 0;
}
.dept-header {
  display: flex;
  // justify-content: space-between;
  align-items: center;
  position: absolute;
  top: 21px;
  .icon{
    width: 16px;
    height: 16px;
    margin-left: 8px;
    flex-shrink: 0;
  }
  .header-crumb {
    display: flex;
    align-items: center;
    max-width: calc(100vw - 520px);
    margin-right: 20px;
    padding-left: 5px;
    ::v-deep .el-breadcrumb__inner {
      font-size: 14px;
      color: #999;
    }
    .crumb-active {
      ::v-deep .el-breadcrumb__inner {
        color: #406EFF;
        cursor: pointer;
      }
    }
    ::v-deep .el-breadcrumb{
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis !important;
      display: flex;
      white-space: nowrap;
    }
  }
}
.page-container {
  .box {
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 14px;
    justify-content: space-between;
    padding: 5px;
    &:hover {
      background: #f5f5f5;
    }
    .text {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: 1;
    }
    .box-content {
      display: flex;
      align-items: center;
      font-weight: bold;
      font-size: 14px;
      width: 100%;
      > img {
        margin-right: 12px;
        background-color: #EFF3FB;
        width: 32px;
        height: 32px;
      }
      .dept-tag {
        border-radius: 4px;
        width: 32px;
        height: 32px;
        padding: 7px;
      }
      .avatar {
        border-radius: 50%;
      }
      .user-info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .user-tag {
          border: none;
          border-radius: 999px;
          padding: 0 8px;
        }
        .post {
          color: #999;
          font-weight: normal;
          font-size: 12px;
          margin-top: 6px;
        }
      }
    }
  }
}
.flex {
  display: flex;
  align-items: center;
}
.next-level {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #999999;
  border-left: 1px solid #eee;
  padding-left: 9px;
  margin-left: 9px;
  img {
    width: 12px;
    margin-right: 4px;
  }
}
</style>
